wx.cloud.init({
  env: 'onpush-eea31f',
  traceUser: true,
});

const db = wx.cloud.database();

const databaseAdd = (data, callback, dbName) => {
  if (!data) {
    data = {
      _id: "123145123",
      description: 'learn cloud database',
      due: new Date('2018-09-01'),
      tags: [
        'cloud',
        'database'
      ],
      location: new db.Geo.Point(113, 23),
      done: false
    }
  }
  console.log(data);
  db.collection('data_list').add({
      // data 字段表示需新增的 JSON 数据
      data: data
    })
    .then(res => {
      console.log(res)
      typeof callback == 'function' ? callback(res) : callback;
    })
    .catch((res) => {
      console.log(res.errCode);
      // -502001 无法添加 已经有同样id的数据了
      databaseUpdate({
        _id: "123145123"
      });
    })
}

const databaseSearch = (data, callback, dbName) => {
  if (!dbName) {
    dbName = "data_list"
  }
  db.collection(dbName).where({
    _id:db.command.in(data)
  }).get().then(res => {
    console.log(res.data)
    typeof callback == 'function' ? callback(res) : callback;
  })
}

const databaseUpdate = (data, reslove, reject) => {
  if (!data) {
    data = {
      description: 'learn cloud database  1234561',
      due: new Date('2018-09-01'),
      tags: [
        'clou22222d',
        'database'
      ],
      location: new db.Geo.Point(113, 23),
      done: true
    }
  }
  console.log(data)
  // return new Promise(() => {
  var _id = data._id;
  console.log(_id);
  delete data._id;
  delete data._openid;
  var list = data;
  console.log(list);
  db.collection('data_list').doc(data._id).update({
    data: list,
    })
    .then((res)=>{
      typeof reslove == "function" ? reslove(res) : reslove;
    })
    .catch((res)=>{
      typeof reject == "function" ? reject(res) : reject;
    })
}


//接口暴露
module.exports = {
  databaseAdd, //添加数据库
  databaseSearch, //搜索数据库
  databaseUpdate, //更新数据库
}